import React, {forwardRef, lazy, useEffect, useRef, useState} from 'react';
import style from './FrontHeader.module.scss'
import {useNavigate, useLocation} from "react-router-dom";
import {Avatar, Dropdown, Form, Input, message, Modal, Radio, Space} from "antd";
import {adduser, retrievePassword} from "./FrontHeaderApi";
import {connect} from "react-redux";
import {loginUserAction, logOutSystem} from "../../store/actions/userActions";
import rules from "../../utils/formVerify";
import {UserOutlined} from "@ant-design/icons";


const PersonalData = lazy(() => import('../PersonalData/PersonalData'))
// 登录
const PageLogin = forwardRef((props, ref) => {
    return (
        <Form
            name="basic"
            labelCol={{span: 6,}}
            ref={ref}
            wrapperCol={{span: 14,}}
            style={{maxWidth: 600,}}
            validateTrigger="onBlur"
            initialValues={{remember: true,}}
            autoComplete="off">
            <Form.Item
                label="账号"
                name="userNumber"
                placeholder="请输入账号，首次登录账号为注册手机号"
                rules={rules[0]}
            >
                <Input/>
            </Form.Item>
            <Form.Item
                label="密码"
                name="password"
                placeholder="请输入密码"
                rules={rules[1]}
            >
                <Input.Password/>
            </Form.Item>
        </Form>
    )
})

// 注册
const PageRegister = forwardRef((props, ref) => {
    return (
        <Form
            name="basic"
            ref={ref}
            labelCol={{span: 6,}}
            wrapperCol={{span: 14,}}
            style={{maxWidth: 600,}}
            initialValues={{remember: true,}}
            autoComplete="off">
            <Form.Item
                label="邮箱"
                name="userEmail"
                rules={rules[4]}
            >
                <Input/>
            </Form.Item>
            <Form.Item
                label="手机"
                name="userPhone"
                rules={rules[3]}
            >
                <Input/>
            </Form.Item>
            <Form.Item
                label="昵称"
                name="userName"
                rules={rules[2]}
            >
                <Input/>
            </Form.Item>
            <Form.Item label="性别" name="userSex" rules={rules[5]}>
                <Radio.Group>
                    <Radio value="男"> 男 </Radio>
                    <Radio value="女"> 女 </Radio>
                </Radio.Group>
            </Form.Item>
            <Form.Item
                label="密码"
                name="password"
                rules={rules[1]}
            >
                <Input.Password/>
            </Form.Item>
        </Form>
    )
})

// 忘记密码
const RetrievePassword = forwardRef((props, ref) => {
    return (
        <Form
            name="basic"
            ref={ref}
            labelCol={{span: 6,}}
            wrapperCol={{span: 14,}}
            style={{maxWidth: 600,}}
            initialValues={{remember: true,}}
            autoComplete="off">
            <Form.Item
                label="账号"
                name="userNumber"
                rules={rules[0]}
            >
                <Input/>
            </Form.Item>
            <Form.Item
                label="邮箱"
                name="userEmail"
                rules={rules[4]}
            >
                <Input/>
            </Form.Item>
            <Form.Item
                label="手机"
                name="userPhone"
                rules={rules[3]}
            >
                <Input/>
            </Form.Item>
            <Form.Item
                label="新密码"
                name="password"
                rules={rules[1]}
            >
                <Input.Password/>
            </Form.Item>
        </Form>
    )
})


function FrontHeader(props) {
    const Navigate = useNavigate()
    const Location = useLocation()
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [messageApi, contextHolder] = message.useMessage();
    const [currentPageKey, setCurrentPageKey] = useState('')
    const [value4, setValue4] = useState('登录');
    const PageLoginFormRef = useRef()
    const PageRegisterFormRef = useRef()
    const retrievePasswordFormRef = useRef()
    const PersonalDataRef = useRef()   //个人资料ref

    const optionsWithDisabled = [
        {
            label: '登录',
            value: '登录',
        },
        {
            label: '注册',
            value: '注册',
        },
        {
            label: '忘记密码',
            value: '忘记密码',
        },
    ];

    const DropdownItem = [
        {
            key: '1',
            label: (
                <div onClick={() => PersonalDataRef.current.showModal()}>
                    个人资料
                </div>
            ),
        },
        {
            key: '2',
            label: (
                <div style={{textAlign: "center"}} onClick={() => props.logOutSystem()}>
                    退出
                </div>
            ),
        },
    ]

    const isCurrentPageKey = (index) => {
        if (currentPageKey === index) {
            return style.currentPageKeyCss
        } else {
            return undefined
        }
    }


    // 导航条切换页面
    const goToPage = (index) => {
        Navigate(index)
        setCurrentPageKey(index)
    }
    // 登录按钮
    const showModal = () => {
        setIsModalOpen(true);
    };


    // 登录弹框确定按钮
    const handleOk = () => {
        if (value4 === '登录') {
            // 登录
            PageLoginFormRef.current.validateFields().then(res => {
                const userData = PageLoginFormRef.current.getFieldsValue()
                props.loginUserAction(userData).then(res => {
                    if (res.code === '200') {
                        messageApi.success('登录成功')
                    } else if (res.code === '201') {
                        messageApi.warning('该账号已存在')
                    } else {
                        messageApi.error(res.message)
                    }
                }).catch(e => {
                    messageApi.error('注册失败，请联系管理员')
                })
                setIsModalOpen(false);
            }).catch(e => {
                messageApi.error('注册失败，请联系管理员')
            })

        } else if (value4 === '注册') {
            // 注册
            PageRegisterFormRef.current.validateFields().then(res => {
                const userData = PageRegisterFormRef.current.getFieldsValue()
                userData.userNumber = userData.userPhone
                adduser(userData).then(res => {
                    if (res.code === '200') {
                        messageApi.success('注册成功')
                        setValue4('登录');
                    } else {
                        messageApi.error(res.message)
                    }
                }).catch(e => {
                    console.log(e)
                })
            }).catch(e => {
                console.log(e)
            })
        } else {
            // 找回密码
            retrievePasswordFormRef.current.validateFields().then(ref => {
                const userData = retrievePasswordFormRef.current.getFieldsValue()
                // userData.userNumber = userData.userNumber
                // userData.userPhone = userData.userPhone
                retrievePassword(userData).then(res => {
                    if (res.code === '200') {
                        messageApi.success('找回成功吗，前往登录')
                        setValue4('登录');
                    } else {
                        messageApi.error(res.message)
                    }
                }).catch(e => {
                    console.log(e)
                })
            }).catch(e => {
                console.log(e)
            })

        }
    };

    // 登录弹取消按钮
    const handleCancel = () => {
        setIsModalOpen(false);
    };


    // 登录启用注册的切换
    const onChange4 = ({target: {value}}) => {
        setValue4(value);
    };

    // 单选框切换
    const radioCut = () => {
        if (value4 === '登录') {
            return <PageLogin ref={PageLoginFormRef}></PageLogin>
        } else if (value4 === '注册') {
            return <PageRegister ref={PageRegisterFormRef}></PageRegister>
        } else {
            return <RetrievePassword ref={retrievePasswordFormRef}></RetrievePassword>
        }
    }

    // 登录和未登录的组件的切换
    const idLoginState = () => {
        const url = props.user ? props.user.userPhotoUrl : ''
        if (props.token) {
            return (
                <Dropdown
                    placement="bottom"
                    menu={{items: DropdownItem}}>
                    <Space>
                        {url ? <Avatar src={url} style={{backgroundColor: '#CCCCCC'}} size="large"
                                       icon={<UserOutlined/>}/> :
                            <Avatar style={{backgroundColor: '#CCCCCC'}} size="large" icon={<UserOutlined/>}/>}

                    </Space>
                </Dropdown>
            )
        } else {
            return (
                <div onClick={showModal}><Space>登录</Space></div>
            )
        }
    }

    //页面刷新的时候匹配导航条路由
    useEffect(() => {
        setCurrentPageKey(Location.pathname)
    }, [])

    return (
        <div className={style.FrontHeader}>
            {contextHolder}
            <div className={style.divLeft}></div>
            <div className={style.divCenter}>
                <div className={isCurrentPageKey('/HomePage')} onClick={() => goToPage('/HomePage')}>
                    <span>首页</span>
                </div>
                <div className={isCurrentPageKey('/HomePage/NoteList')} onClick={() => goToPage('/HomePage/NoteList')}>
                    <span>目录</span>
                </div>
                <div className={isCurrentPageKey('/HomePage/LiveRecord')}
                     onClick={() => goToPage('/HomePage/LiveRecord')}>
                    <span>生活</span>
                </div>
                <div className={isCurrentPageKey('/HomePage/MessageBoard')}
                     onClick={() => goToPage('/HomePage/MessageBoard')}>
                    <span>留言板</span>
                </div>
                <div className={isCurrentPageKey('/HomePage/DataStatistics')}
                     onClick={() => goToPage('/HomePage/DataStatistics')}>
                    <span>数据统计</span>
                </div>
            </div>
            <div className={style.divRight}>
                {idLoginState()}
            </div>
            <Modal title="欢迎来到我的博客~~"
                   open={isModalOpen}
                   onOk={handleOk}
                   onCancel={handleCancel}
            >
                <div style={{padding: '10px'}}>
                    {radioCut()}
                </div>
                <Radio.Group
                    options={optionsWithDisabled}
                    onChange={onChange4}
                    value={value4}
                    optionType="button"
                    buttonStyle="solid"
                />
            </Modal>
            <PersonalData ref={PersonalDataRef}> </PersonalData>
        </div>
    );
}

const mapStateToProps = (state) => {
    return {user: state.UserRedux.user, token: state.UserRedux.token}
}
const mapDispatchToProps = {
    loginUserAction, logOutSystem
}

export default connect(mapStateToProps, mapDispatchToProps)(FrontHeader);
